package config.java;

import java.io.File;
import java.io.FileInputStream;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * 以sun规定的xml格式的配置文件<br>
 * 这种配置文件是xml文件，但其格式必须是以下格式：
 * 
 * <pre>
 * &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
 *  &lt;!DOCTYPE properties SYSTEM &quot;http://java.sun.com/dtd/properties.dtd&quot;&gt;
 *  &lt;properties&gt;
 *  	&lt;entry key=&quot;msg01&quot;&gt;Message 01&lt;/entry&gt;
 *  	&lt;entry key=&quot;msg02&quot;&gt;Message 02&lt;/entry&gt;
 *  	&lt;entry key=&quot;msg03&quot;&gt;Message 03&lt;/entry&gt;
 *  &lt;/properties&gt;
 *  其中&lt;!DOCTYPE properties SYSTEM &quot;http://java.sun.com/dtd/properties.dtd&quot;&gt;这行不能少。
 * </pre>
 * 
 * 如果不是这种格式，会抛出 格式不符错误
 * 
 * @author liao
 * 
 */
public class PropertyXmlConfig extends ParseConfig {

	@Override
	protected void parse(String alias, String file) {
		ConfigLog.debugLog("Property XML Config load file:" + file);
		File f = null;
		FileInputStream fi = null;
		ConfigValue value = ConfigValue.getInstance();
		ConfigBin b = value.getConfBin(alias);
		if (b == null)
			b = new ConfigBin();
		if (b != null) {
			b.setAlias(alias);
			b.setFile(file);
			b.setLoadTime(System.currentTimeMillis());
		}
		try {
			Properties p = new Properties();
			f = new File(file);
			fi = new FileInputStream(f);
			p.loadFromXML(fi);
			Iterator itr = p.entrySet().iterator();
			Hashtable<String, String> pv = new Hashtable<String, String>();
			while (itr.hasNext()) {
				Map.Entry e = (Map.Entry) itr.next();
				pv.put((String) e.getKey(), (String) e.getValue());
			}

			if (pv.size() > 0)
				value.setConfigValue(alias, pv);

			ConfigLog.debugLog("Property XML Config file:" + file
					+ " load success!");
			if (b != null)
				b.setStatus(1);
		} catch (Exception ex) {
			ConfigLog.errorLog("Property XML Config file:" + file
					+ " load failed!");
			ConfigLog.errorLog(ex);
			if (b != null) {
				b.setStatus(-1);
				b.setError(ex.toString());
			}
		} finally {
			if (fi != null) {
				try {
					fi.close();
					fi = null;
				} catch (Exception e) {
				}
			}
			if (f != null) {
				f = null;
			}
			value.setConf(b);
		}
	}

}
